import React, { useState, useRef, useEffect } from 'react';
import { QuestionCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Checkbox, Popconfirm, Button, DatePicker, Modal, Input, Descriptions, Tooltip, Row, Col } from 'antd';
import type { FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import { useModel, history } from 'umi';
import Detail from './Detail';
import Refund from './comm/Refund';
import { getOnceOrderList, updateOnceOrderStatus, getOnceOrderCount, managerCancel, getLensesOrderFileToken } from '@/services/order/api';
import { OrderStatus, OptType } from '@/utils/constants';
import { showMsg, MsgType, formatDate, getDateValue, currentDate, isNull, isSupportSticky, isScroll, isExits } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import TableHint from '@/components/TableHint/Index';
import { ModalForm, ProFormDatePicker, ProFormFieldSet, ProFormSelect } from '@ant-design/pro-form';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import ChoicePatient from '@/components/ChoicePatient/list';
import './style.less';
import { followUpPartake, getFollowUpPartake, getSurveyList } from '@/services/patient/followUpApi';
import EyeInfoModal from './index_eyeInfo';
import moment from 'moment';
import { getSupplierList } from '@/services/stock-goods/api';

const OneTimeOrderList: React.FC = (props) => {
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const { info } = Modal;
  const { initialState } = useModel('@@initialState');
  const isEyeDept = initialState?.currentUser?.dept_type === 'Y';

  const [totalObj, setTotalObj] = useState([]);

  // 表格选中行
  const [currentRow, setCurrentRow] = useState<ORDERAPI.OnceOrderItem>({});

  // 已支付数
  const [payNum, setPayNum] = useState<number>(0);

  // 待退款数量
  const [waitRefundNum, setWaitRefundNum] = useState<number>(0)

  const [loading, setLoading] = useState(false);

  // 用于存储其他搜索条件
  const [otherParams, setOtherParams] = useState({ order_status: '', begin_date: '', end_date: '' });

  // 身份证/病案号
  const [inputNo, setInputNo] = useState('');

  // 当前选中的行编号，用于定位颜色
  const [clickRow, setClickRow] = useState('');

  // 取消出院办结订单的弹窗
  const [showCancel, setShowCancel] = useState(false);

  // 详情弹窗
  const [detailVisible, setDetailVisible] = useState<boolean>(false);

  // 退款弹窗
  const [refundVisible, setRefundVisible] = useState<boolean>(false);
  // 随访表弹窗
  const [surveyReadonly, setSurveyReadonly] = useState<boolean>(false);
  const [followUpOpen, setFollowUpOpen] = useState<boolean>(false);
  const [followUpOptions, setFollowUpOptions] = useState<any[]>();
  const followUpFormRef = useRef<FormInstance>();
  // 直接修改验光信息
  const [eyeInfoModalOpen, setEyeInfoModalOpen] = useState<boolean>(false);
  // 导出镜片订单
  const [exportLensesOrder, setExportLensesOrder] = useState<boolean>(false);
  const [supplierOptions, setSupplierOptions] = useState<any[]>();

  // 表单筛选项查询
  const forFormSearch = () => {
    setOtherParams({ order_status: '' });
    formRef.current?.submit();
  }

  /**
   * 更新订单状态
   * @param record
   * @param order_status
   */
  const updateOrderStatus = async (record: ORDERAPI.OnceOrderItem, order_status: string) => {
    try {
      const data = {
        order_id: record.order_id as string,
        order_status
      };
      await updateOnceOrderStatus(data);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  // 记录详情页返回的数据
  // useEffect(() => {
  //   console.log('query?.from', query?.from)
  //   if (query?.from !== 'detail') {
  //     setCache('once_order', '');
  //     formRef.current?.setFieldsValue({
  //       plan_create_time: [currentDate(), '', currentDate()]
  //     });
  //     formRef.current?.submit();
  //     return
  //   }
  //   let searchCondition = getCache('once_order');
  //   searchCondition = JSON.parse(searchCondition || '{}');

  //   formRef.current?.setFieldsValue({
  //     plan_create_time: [
  //       searchCondition.begin_date ? parseDate(searchCondition.begin_date) : currentDate(),
  //       '',
  //       searchCondition.end_date ? parseDate(searchCondition.end_date) : currentDate()
  //     ],
  //     admission_num: searchCondition.admission_num,
  //     patient_name: searchCondition.patient_name,
  //     order_status: searchCondition.order_status,
  //     order_person: searchCondition.order_person,
  //     identity_no: searchCondition.identity_no,
  //     not_status_list: searchCondition.not_status_list
  //   });
  //   formRef.current?.submit();
  // }, [])

  // 操作列 随访 按钮
  const renderFollowUpButton = (record: ORDERAPI.OnceOrderItem) => (
    isEyeDept ?
      <a key="followUp" onClick={() => {
        setCurrentRow(record);
        setFollowUpOpen(true);
        getFollowUpPartake(record.order_id as string).then(res => {
          if (res) {
            followUpFormRef.current?.setFieldsValue({
              survey_test_id: res.survey_test_id,
              survey_date: res.survey_date
            });
            if (res.survey_date && moment().diff(moment(res.survey_date), 'seconds') >= 0) {
              setSurveyReadonly(true);
            } else {
              setSurveyReadonly(false);
            }
          }
        });
      }}> 随访</a>
      : <></>
  );

  // 操作列 验光信息 按钮
  const renderEyeInfoButton = (record: ORDERAPI.OnceOrderItem) => (
    isEyeDept
      ?
      <a key="eyeInfo" onClick={() => {
        setEyeInfoModalOpen(true);
        setCurrentRow(record);
      }}>配镜信息</a>
      :
      <></>
  );

  // 列配置
  const columns: ProColumns<ORDERAPI.OnceOrderItem>[] = [
    {
      title: '下单时间',
      hideInTable: true,
      dataIndex: 'order_time',
      renderFormItem: () => {
        return <ProFormFieldSet wrapperCol={{ style: { width: '100%' } }}>
          <DatePicker allowClear={false} style={{ width: '100%' }} />
          <span style={{ padding: '0 5px' }}>-</span>
          <DatePicker allowClear={false} style={{ width: '100%' }} />
        </ProFormFieldSet>
      },
      order: 7,
    },
    {
      title: '身份证/病案号',
      dataIndex: 'input_no',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ChoicePatient
            caseNoKey={initialState?.canAll ? 'out_case_no' : 'case_no'}
            showMore
            onChoice={(e) => setInputNo(e.visit_no)}
          />
        );
      },
      order: 5,
      formItemProps: {
        labelCol: { flex: '0 0 100px' }
      }
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入患者姓名" />
        );
      },
      order: 6,
    },
    {
      title: '订单状态',
      dataIndex: 'order_status',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        C: '已开单',
        W: '待支付',
        P: '已支付',
        F: '已完成',
        E: '已作废',
        A: '退款待审批',
        R: '已退款'
      },
      order: 2,
      formItemProps: {
        labelCol: { flex: '0 0 100px' }
      }
    },
    {
      title: '姓名',
      dataIndex: 'patient_name',
      search: false,
      width: 70,
    },
    {
      title: '性别',
      dataIndex: 'patient_sex_name',
      search: false,
      width: 40,
    },
    {
      title: '身份证/住院号/就诊卡号',
      dataIndex: 'identity_no',
      search: false,
      className: 'wordbreak',
      width: 150,
      render: (_, record) => {
        return record.identity_no || record.admission_num || record.ic_card_no;
      }
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 100,
      order: 4,
    },
    {
      title: '订单号',
      dataIndex: 'order_id',
      width: 160,
      search: false
    },
    {
      title: '下单时间',
      dataIndex: 'create_time',
      search: false,
      width: isScroll ? 82 : 130,
      render: (_, record) => {
        return record.create_date + ' ' + record.create_time;
      }
    },
    {
      title: '开单科室',
      dataIndex: 'create_dept_name',
      width: 100,
      search: false
    },
    {
      title: '商品所属科室',
      dataIndex: 'goods_dept_name',
      width: 100,
      search: false
    },
    {
      title: '结算金额',
      dataIndex: 'sett_price',
      width: 80,
      valueType: 'money',
      align: 'right',
      search: false
    },
    {
      title: '渠道信息',
      dataIndex: 'pay_channel',
      width: 70,
      search: false,
      render: val => val === 'P' ? 'PC管理端' : val === 'M' ? '小程序端' : '出院办结'
    },
    {
      title: '责任人',
      dataIndex: 'order_person',
      width: 70,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入责任人" />
        );
      },
      order: 3,
    },
    {
      title: '搜索结果不包括',
      dataIndex: 'not_status_list',
      hideInTable: true,
      order: 1,
      formItemProps: {
        labelCol: { flex: '0 0 108px' }
      },
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Checkbox.Group
            defaultValue={['E', 'F']}
            options={
              [
                {
                  label: '已完成',
                  value: 'F'
                },
                {
                  label: '已作废',
                  value: 'E'
                }
              ]
            }
          />
        );
      }
    },
    {
      title: '订单状态',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : false,
      width: 60,
      align: 'center',
      search: false,
      render: (_, record) => {
        // 订单状态 C：开单状态，W：待支付，P：已支付，F：已完成，E：已作废，A：退款待审批， R：已退款  U: 退款处理中
        if (['C', 'E', 'F', 'P'].includes(record.order_status as string)) {
          return OrderStatus[record.order_status as string];
        }

        // 已退款
        if (record.order_status === 'R') {
          const isAll = record.refund_price === record.sett_price; // 全部退款
          return isAll ? '已退款' : <div>
            <div>部分退款</div>
            <div>￥{record.refund_price}</div>
          </div>
        }
        // 待支付
        if (record.order_status === 'W') {
          return <div>
            <div>{OrderStatus[record.order_status as string]}</div>
            <div>{`${record.pay_valid_time}前`}</div>
          </div>
        }

        // 退款待审批
        if (record.order_status === 'A') {
          return <div>
            <div>{OrderStatus[record.order_status as string]}</div>
            <div>￥{record.refund_price}</div>
          </div>
        }
        // 退款处理中
        if (record.order_status === 'U') {
          return <div>
            <div>{OrderStatus[record.order_status as string]}</div>
            <div>{record.refund_price}</div>
          </div>
        }
        return OrderStatus[record.order_status as string];
      }
    },
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : false,
      width: isEyeDept ? 290 : 240,
      align: 'center',
      render: (_, record) => {
        // 订单状态 C：开单状态，W：待支付，P：已支付，F：已完成，E：已作废，A：退款待审批， R：已退款, U: 退款处理中

        // 退款待审批
        if (record.order_status === 'A') {
          return [
            <PermissionControl action_id="400400009">
              <a key="aduit" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>审批</a>
            </PermissionControl>
            ,
            renderEyeInfoButton(record) // 验光信息按钮
            ,
            renderFollowUpButton(record) // 随访按钮
          ]
        }

        // 开单状态 || 待支付
        if (record.order_status === 'C' || record.order_status === 'W') {
          return [
            <PermissionControl action_id="400400002">
              <a key="view" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>
            ,
            // manager_flag为Y代表已办理【出院办结】，已办理【出院办结】的患者，不可修改和取消订单
            record.manager_flag !== 'Y' &&
            <PermissionControl action_id="400400003">
              <a key="edit" onClick={() => {
                history.push({
                  pathname: '/order/one-time-order/doctor-bill',
                  query: {
                    order_id: record.order_id as string,
                    type: OptType.EDIT
                  }
                });
              }}>修改</a>
            </PermissionControl>
            ,
            <PermissionControl action_id="400400004">
              {
                record.manager_flag !== 'Y' ?
                  <Popconfirm
                    placement="topRight"
                    key="cancel"
                    title={record.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : "您即将取消订单，是否继续？"}
                    onConfirm={async () => {
                      await updateOrderStatus(record, 'E').then(res => {
                        if (res) {
                          showMsg('订单已取消', MsgType.SUCCESS);
                        }
                        actionRef.current?.reload();
                      }).catch(error => {
                        showMsg(error?.data?.errmsg)
                      });
                    }}
                    okText="确认取消"
                    cancelText="再想想">
                    <a>取消</a>
                  </Popconfirm> :
                  <a onClick={() => {
                    setCurrentRow(record);
                    setShowCancel(true);
                  }}>取消</a>
              }
            </PermissionControl>
            ,
            renderEyeInfoButton(record) // 验光信息按钮
            ,
            renderFollowUpButton(record) // 随访按钮
          ]
        }

        // 已作废
        if (record.order_status === 'E') {
          return [
            <PermissionControl action_id="400400002">
              <a key="view" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>,
            <PermissionControl action_id="400400010">
              <a key="reopen" onClick={() => {
                history.push({
                  pathname: '/order/one-time-order/doctor-bill',
                  query: {
                    order_id: record.order_id as string,
                    type: 'reopen'
                  }
                });
              }}>重新开单</a>
            </PermissionControl>
            ,
            renderEyeInfoButton(record) // 验光信息按钮
            ,
            renderFollowUpButton(record) // 随访按钮
          ]
        }

        // 已完成
        if (record.order_status === 'F') {
          return [
            <PermissionControl action_id="400400002">
              <a key="view" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>,
            // 未办理出院办结||已完成 的订单可以进行退款申请
            (record.manager_flag !== 'Y' || record.order_status === 'F') &&
            <PermissionControl action_id="400400006">
              <a key="refund" onClick={() => {
                setRefundVisible(true);
                setCurrentRow(record);
              }}>退款</a>
            </PermissionControl>,
            <PermissionControl action_id="400400010">
              <a key="reopen" onClick={() => {
                history.push({
                  pathname: '/order/one-time-order/doctor-bill',
                  query: {
                    order_id: record.order_id as string,
                    type: 'reopen'
                  }
                });
              }}>重新开单</a>
            </PermissionControl>
            ,
            renderEyeInfoButton(record) // 验光信息按钮
            ,
            renderFollowUpButton(record) // 随访按钮
          ]
        }

        // 已支付
        if (record.order_status === 'P') {
          return [
            <PermissionControl action_id="400400002">
              <a key="view" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>,
            // 未办理出院办结||已支付 的订单可以进行完成交付
            (record.manager_flag !== 'Y' || record.order_status === 'P') &&
            <PermissionControl action_id="400400005">
              <Popconfirm
                key="complete"
                placement="topRight"
                onConfirm={async () => {
                  try {
                    await updateOnceOrderStatus({
                      order_id: record.order_id as string,
                      order_status: 'F'
                    })
                    showMsg('订单已完成', MsgType.SUCCESS)
                    actionRef.current?.reload()
                  } catch (error) {
                    showMsg(error?.data?.errmsg)
                  }
                }}
                cancelText="再想想"
                title="此商品已交付患者，是否确认？">
                <a>完成</a>
              </Popconfirm>
            </PermissionControl>,
            // 未办理出院办结||已支付 的订单可以进行退款申请
            (record.manager_flag !== 'Y' || record.order_status === 'P') &&
            <PermissionControl action_id="400400006">
              <a key="refund" onClick={() => {
                setRefundVisible(true);
                setCurrentRow(record);
              }}>退款</a>
            </PermissionControl>,
            <PermissionControl action_id="400400010">
              <a key="reopen" onClick={() => {
                history.push({
                  pathname: '/order/one-time-order/doctor-bill',
                  query: {
                    order_id: record.order_id as string,
                    type: 'reopen'
                  }
                });
              }}>重新开单</a>
            </PermissionControl>
            ,
            renderEyeInfoButton(record) // 验光信息按钮
            ,
            renderFollowUpButton(record) // 随访按钮
          ]
        }

        // 已退款/退款中
        if (record.order_status === 'R' || record.order_status === 'U') {
          return [
            <PermissionControl action_id="400400002">
              <a key="view" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>
            ,
            renderEyeInfoButton(record) // 验光信息按钮
            ,
            renderFollowUpButton(record) // 随访按钮
          ]
        }

        <PermissionControl action_id="400400010">
          <a key="reopen" onClick={() => {
            history.push({
              pathname: '/order/one-time-order/doctor-bill',
              query: {
                order_id: record.order_id as string,
                type: 'reopen'
              }
            });
          }}>重新开单</a>
        </PermissionControl>
        return []
      }
    }
  ];

  // 退款审批回调
  const optCallback = (data: any) => {
    // 审批通过
    if (data.type === 1) {
      const orderSumbitConfig = {
        title: '',
        content: '退款请求已审批发送至结算中心，退款会原路返回至支付账户。'
      };
      info(orderSumbitConfig);
      actionRef.current?.reload();
      return
    }

    // 审批拒绝
    if (data.type === 2) {
      const orderSumbitConfig = {
        title: '',
        content: '退款审批已拒绝。'
      };
      info(orderSumbitConfig);
      actionRef.current?.reload();
      return
    }
    // 提交退款申请
    if (data.type === 3) {
      const orderSumbitConfig = {
        title: '',
        content: '退款请求已提交，等待审批。'
      };
      info(orderSumbitConfig);
      actionRef.current?.reload();
      return
    }

    // 提交支付
    // const orderSumbitConfig = {
    //   title: '',
    //   content: `订单提交成功，请在【${data.pay_valid_time}】前完成缴费`
    // };
    // info(orderSumbitConfig);
    actionRef.current?.reload();
  }

  useEffect(() => {
    // let searchCondition = getCache('once_order');
    // searchCondition = JSON.parse(searchCondition || '{}');

    // formRef.current?.setFieldsValue({
    //   order_time: [
    //     searchCondition.begin_date ? parseDate(searchCondition.begin_date) : currentDate(),
    //     '',
    //     searchCondition.end_date ? parseDate(searchCondition.end_date) : currentDate()
    //   ],
    //   patient_name: searchCondition.patient_name,
    //   plan_status: searchCondition.plan_status,
    //   not_status_list: searchCondition.not_status_list || ['E', 'F']
    // });
    // formRef.current?.submit();
    // console.log('isSupportSticky', isSupportSticky());
    // 初始化搜索表单：下单时间默认查询当天的、搜索结果不包括：已完成、已作废
    formRef.current?.setFieldsValue({
      order_time: [
        currentDate(),
        '',
        currentDate(),
      ],
      not_status_list: ['E', 'F']
    });
    formRef.current?.submit();

    // 获取随访表列表
    getSurveyList({ current: 1, pageSize: 99 }).then(res => {
      const options = res.record_list.map(({ survey_id, survey_title }) => ({
        value: survey_id, label: survey_title
      }));
      setFollowUpOptions(options);
    });

    // 获取供应商列表
    getSupplierList().then(res => {
      const options = res.record_list.map(({ supplier }) => ({
        value: supplier, label: supplier
      }));
      setSupplierOptions(options);
    });
  }, [])

  // 获得汇总数据
  const getTotal = async (params) => {
    if (isExits('400400011')) {
      await getOnceOrderCount(params).then(res => {
        setTotalObj(res);
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      })
    }
  }

  return (
    <PageContainer
      className="one-time-order-container"
      extra={[
        <BreadcrumbDept />
      ]}
      breadcrumb={{}}
    >
      <ProTable<ORDERAPI.OnceOrderItem, ORDERAPI.OnceOrderItem & { order_time?: string[]; begin_date?: string; end_date?: string; } & COMMON.PageParams>
        rowKey="order_id"
        actionRef={actionRef}
        formRef={formRef}
        bordered
        options={false}
        manualRequest={true}
        polling={30000} // 每30秒刷新表格一次
        loading={loading}
        request={async (params) => {
          console.log('params', params);
          const { order_time } = params;
          if (order_time) {
            params.begin_date = order_time[0] && formatDate(order_time[0], 'YYYYMMDD');
            params.end_date = order_time[2] && formatDate(order_time[2], 'YYYYMMDD');
          }

          // 根据输入的判断是 就诊卡号、身份证号还是住院号  start
          if (inputNo.length >= 10 && inputNo.length < 15) { // 就诊卡号
            params.ic_card_no = inputNo;
            params.admission_num = '';
            params.identity_no = '';
          } else if (inputNo.length >= 15) { // 身份证号
            params.identity_no = inputNo;
            params.admission_num = '';
            params.ic_card_no = '';
          } else { // 住院号
            params.ic_card_no = '';
            params.identity_no = '';
            params.admission_num = inputNo;
          }
          // 根据输入的判断是 就诊卡号、身份证号还是住院号  end

          for (const prop in params) {
            if (!params[prop]) {
              delete params[prop];
            }
          }
          if (order_time && order_time[0] && order_time && order_time[2]) {
            if (getDateValue(order_time[0]) > getDateValue(order_time[2])) {
              showMsg('下单结束时间不能早于开始时间', MsgType.INFO);
              return;
            }
          }
          delete params.order_time;
          console.log('therParams', otherParams)
          // 如果用户单独点击了页面上的【查看已支付订单】【查看退款申请单】，请求接口的时候，则只传订单状态筛选，但页面上表单搜索信息则保留
          if (!isNull(otherParams.order_status)) {
            params = {
              ...otherParams,
              current: params.current,
              pageSize: params.pageSize,
            };
          }
          // setCache('once_order', JSON.stringify(params));
          setLoading(true);
          try {
            getTotal(params);
            const data: ORDERAPI.OnceOrderItemList = await getOnceOrderList(params);
            setPayNum(data.pay_num); // 设置已支付订单数
            setWaitRefundNum(data.wait_refund_num); // 设置待退款审批订单数
            setLoading(false);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            }
          } catch (error) {
            setLoading(false);
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            }
          }
        }}
        search={{
          span: 8,
          labelWidth: 70,
          collapsed: false,
          collapseRender: false,
          style: { padding: '0 12px' },
          optionRender: () => [
            <Button type='primary' onClick={() => {
              forFormSearch();
            }}>查询</Button>
          ]
        }}
        className='mytable onceOrderTable'
        toolBarRender={() => <div>
          {
            isExits('400400011') &&
            <div>
              <Descriptions className='onceOrderTotal' size="small" column={{ xl: 3, xxl: 6 }}>
                <Descriptions.Item
                  label={
                    <Tooltip title="应收款额 = 结算金额累加（除已作废状态的所有订单）">
                      应收款额 <QuestionCircleOutlined />
                    </Tooltip>
                  }
                >
                  <span className="green bold">￥{totalObj.total_settle_price}</span>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <Tooltip title="实际收款额 = 结算金额累加（包括已支付/已完成/退款中/已退款状态）">
                      实际收款额 <QuestionCircleOutlined />
                    </Tooltip>
                  }
                >
                  <span className="green bold">￥{totalObj.total_real_settle_price}</span>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <Tooltip title="应退款额 = 退款金额累加（包括退款中/已退款状态）">
                      应退款额 <QuestionCircleOutlined />
                    </Tooltip>
                  }
                >
                  <span className="org bold">￥{totalObj.total_refund_price}</span>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <Tooltip title="实际退款额 = 已退款金额累加">
                      实际退款额 <QuestionCircleOutlined />
                    </Tooltip>
                  }
                >
                  <span className="org bold">￥{totalObj.total_real_refund_price}</span>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <Tooltip title="结余 = 实际收款额 - 实际退款额">
                      结余 <QuestionCircleOutlined />
                    </Tooltip>
                  }
                >
                  <span className="green bold">￥{totalObj.balance_price}</span>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <Tooltip title="已作废 = 已作废金额累加">
                      已作废 <QuestionCircleOutlined />
                    </Tooltip>
                  }
                >
                  <span className="red bold">￥{totalObj.abolish_price}</span>
                </Descriptions.Item>
              </Descriptions>
              <div style={{ marginBottom: 8, height: '1px', borderTop: '1px solid rgba(0, 0, 0, 0.06)' }} />
            </div>
          }
          <div style={{ position: 'relative' }}>
            <PermissionControl action_id="400400001">
              <Button
                onClick={() => {
                  history.push({
                    pathname: '/order/one-time-order/doctor-bill',
                    query: {
                      type: OptType.ADD
                    }
                  });
                }}
                icon={<PlusOutlined />}
                type="primary">
                开单
              </Button>
            </PermissionControl>
            <div style={{ display: 'inline-block', position: 'absolute', right: 0 }}>
              <PermissionControl action_id="400400012">
                <Button type="primary" onClick={() => setExportLensesOrder(true)}>
                  导出镜片订单
                </Button>
              </PermissionControl>
            </div>
          </div>
          {
            (payNum > 0 || waitRefundNum > 0) && <TableHint
              text={
                <div>
                  {payNum > 0 && <span>有 <span><span style={{ color: '#F2232C', fontWeight: 'bold' }}>{payNum}</span> 笔订单已支付 </span></span>}
                  {waitRefundNum > 0 ? <span>{payNum > 0 ? '，' : ''}<span style={{ color: '#F2232C', fontWeight: 'bold' }}>{waitRefundNum}</span> 笔订单已提交退款申请</span> : ''} 。
                </div>}
              onAction={payNum > 0 ? () => {
                // 查看已支付订单，请求接口的时候，则只传订单状态筛选，但页面上表单搜索信息则保留
                setOtherParams({ ...otherParams, order_status: 'P' });
                formRef.current?.submit();
              } : null}
              actionText="查看已支付订单"
              onRefund={waitRefundNum > 0 ? () => {
                // 查看退款申请单，请求接口的时候，则只传订单状态筛选，但页面上表单搜索信息则保留
                setOtherParams({ ...otherParams, order_status: 'A' });
                formRef.current?.submit();
              } : null}
              showAction={payNum > 0} /> // 已支付订单数大于0的时候，显示该按钮
          }
        </div>}
        // scroll={{ x: window.innerWidth < 1400 ? 1250 : null }}
        pagination={{ showQuickJumper: true }}
        columns={columns}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.order_id) }, // 点击行
            onMouseEnter: event => { }, // 鼠标移入行
            onMouseLeave: event => { },
          };
        }}
        rowClassName={(record) => {
          return record.order_id === clickRow ? 'tableRowClick' : '' // 点击行，赋颜色
        }}
        scroll={{ x: 1000 }}
      />


      {
        // 查看弹窗
        detailVisible && <Detail
          handleModalVisible={setDetailVisible}
          record={currentRow}
          optCallback={optCallback}
        />
      }

      {
        // 退款弹窗
        refundVisible &&
        <Refund
          id={currentRow.order_id}
          onFinish={() => {
            setRefundVisible(false);
            actionRef.current.reload();
          }}
          onClose={() => setRefundVisible(false)}
        />
      }
      {
        // 取消按钮的弹窗提示
        showCancel &&
        <Modal
          visible
          title='提示'
          maskClosable={false}
          footer={[<Button onClick={() => {
            setShowCancel(false);
            setCurrentRow({});
          }}>再想想</Button>,
          <Button type='primary' onClick={async () => {
            await managerCancel(currentRow.manager_order_id).then(res => {
              if (isNull(res)) {
                showMsg('支付已取消', 'success');
                actionRef.current?.reload();
                setShowCancel(false);
              }
              setCurrentRow({});
            }).catch(error => {
              showMsg(error?.data?.errmsg)
            });
          }}>取消支付</Button>,
          <Button type='primary' onClick={async () => {
            await managerCancel(currentRow.manager_order_id).then(async () => {
              await updateOnceOrderStatus({ order_id: currentRow.order_id, order_status: 'E' }).then(res => {
                if (res) {
                  showMsg('订单已取消', MsgType.SUCCESS);
                }
                actionRef.current?.reload();
                setShowCancel(false);
                setCurrentRow({});
              }).catch(error => {
                showMsg(error?.data?.errmsg)
              });
            }).catch(error => {
              showMsg(error?.data?.errmsg)
            });
          }}>取消订单</Button>]}
          onCancel={() => {
            setShowCancel(false);
            setCurrentRow({});
          }}
        >
          <ExclamationCircleOutlined style={{ color: '#faad14' }} /> 该笔订单已经通过出院办结发起结算，是否确认取消？
        </Modal>
      }

      {
        // 随访弹窗
        <ModalForm
          formRef={followUpFormRef}
          visible={followUpOpen} title="患者随访" layout='horizontal'
          modalProps={{ bodyStyle: { padding: '24px 38px 12px' }, destroyOnClose: true }}
          onVisibleChange={visible => {
            if (!visible) {
              setCurrentRow({});
            }
            setFollowUpOpen(visible);
          }}
          onFinish={async values => {
            try {
              if (!surveyReadonly) {
                const { order_id, mobile, identity_no, admission_num, ic_card_no, patient_id, patient_name } = currentRow as any;
                const survey_date = values.survey_date && formatDate(values.survey_date, 'YYYYMMDD');
                await followUpPartake({ ...values, order_id, mobile, identity_no, admission_num, ic_card_no, patient_id, patient_name, survey_date });
                showMsg('已设定随访单', 'success');
              }
              setSurveyReadonly(false);
              setFollowUpOpen(false);
            } catch (error: any) {
              showMsg(error?.data?.errmsg);
            }
          }}
        >
          <ProFormSelect
            name="survey_test_id" label="随访调研表" labelCol={{ flex: '86px' }}
            required rules={[{ required: true }]} options={followUpOptions} readonly={surveyReadonly} />
          <ProFormDatePicker
            name="survey_date" label="随访日期" labelCol={{ flex: '86px' }}
            required rules={[{ required: true }]} readonly={surveyReadonly}
            fieldProps={{ style: { width: '100%' }, disabledDate: current => (current && current < moment().endOf("day")) }} />
        </ModalForm>
      }

      {
        // 验光信息
        isEyeDept && <EyeInfoModal visible={eyeInfoModalOpen} editData={currentRow} visibleChange={visible => {
          if (!visible)
            setCurrentRow({})
          setEyeInfoModalOpen(visible);
        }} finishCallback={() => actionRef.current?.reload()} />
      }

      {
        // 导出镜片订单
        exportLensesOrder &&
        <ModalForm
          formRef={followUpFormRef}
          title="导出镜片订单" layout='horizontal'
          modalProps={{ bodyStyle: { padding: '24px 38px 12px' }, destroyOnClose: true }}
          visible onVisibleChange={setExportLensesOrder}
          onFinish={async values => {
            try {
              const { supplier, begin_date_str, end_date_str } = values;
              if (moment(begin_date_str).isAfter(moment(end_date_str))) {
                showMsg('开始时间不能大于结束时间');
                return;
              }
              const res = await getLensesOrderFileToken(begin_date_str.replaceAll('-', ''), end_date_str.replaceAll('-', ''), supplier);
              const token = res?.file_token ?? '';
              if (token == '') {
                showMsg('文件不存在');
                return;
              }
              window.open(`/api/report/${res.file_token}/down`);
              setExportLensesOrder(false);
            } catch (error: any) {
              showMsg(error?.data?.errmsg);
            }
          }}
        >
          <ProFormSelect name="supplier" label="供应商" placeholder='请选择。不选默认所有供应商' labelCol={{ flex: '86px' }} options={supplierOptions} />
          <Row>
            <Col span={13}>
              <ProFormDatePicker
                name="begin_date_str" label="下单日期" labelCol={{ flex: '86px' }} addonAfter='- &nbsp;'
                required rules={[{ required: true, message: '请输入开始时间' }]} placeholder='请输入开始时间'
                fieldProps={{ style: { width: '100%' }, disabledDate: current => (current && current > moment().endOf("day")) }} />
            </Col>
            <Col flex='auto'>
              <ProFormDatePicker
                name="end_date_str" placeholder='请输入结束时间' required rules={[{ required: true, message: '请输入结束时间' }]}
                fieldProps={{ style: { width: '100%' }, disabledDate: current => (current && current > moment().endOf("day")) }} />
            </Col>
          </Row>
        </ModalForm>
      }

    </PageContainer >
  );
};
export default OneTimeOrderList;
